﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace ModbusTCP
{
    //网络操作相关的类
    public class NetDeviceBase
    {
        Socket socket;

        /// <summary>
        /// 接收超时时间
        /// </summary>
        int receiveTimeout;

        /// <summary>
        /// 发送超时时间
        /// </summary>
        int sendTimeout;

        /// <summary>
        /// 连接超时时间
        /// </summary>
        int connectTimeOut;


        public bool Connect(string ip, int port)
        {
            try
            {
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, receiveTimeout);
                socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, sendTimeout);
                IAsyncResult asyncResult = socket.BeginConnect(ip, port, null, null);
                bool connectResult = asyncResult.AsyncWaitHandle.WaitOne(connectTimeOut, false);
                if (connectResult)
                {
                    return true;
                }
                return false;
            }
            catch (Exception e)
            {
                throw new Exception("连接失败：" + e.Message);
            }
        }

        public bool Close()
        {
            if (socket != null)
            {
                socket.Close();
                return true;
            }
            return false;

        }

    }
}
